<template>
  <div class="information-container">
    <Header />
    <div class="information-content">
      <h2>心理资讯</h2>
      
      <div class="content-layout">
        <!-- 资讯列表 -->
        <div class="article-list" v-loading="loading">
          <el-row :gutter="20">
            <el-col 
              :span="24"
              v-for="announcement in announcements" 
              :key="announcement.announcementId"
            >
              <el-card 
                v-if="announcement.announcementId"
                class="article-card" 
                shadow="hover" 
                @click="viewDetail(announcement)"
              >
                <div class="article-info">
                  <div class="article-header">
                    <h3 class="article-title">{{ announcement.title }}</h3>
                    <div class="article-meta">
                      <span class="publish-time">
                        <el-icon><Calendar /></el-icon>
                        {{ formatDate(announcement.createTime) }}
                      </span>
                      <span class="author">
                        <el-icon><User /></el-icon>
                        {{ announcement.name }}
                      </span>
                    </div>
                  </div>
                  <p class="article-summary">{{ parseAnnouncementText(announcement.text) }}</p>
                </div>
              </el-card>
              <div v-else class="empty-card"></div>
            </el-col>
          </el-row>
        </div>
        
        <!-- 分类筛选 -->
        <div class="category-filter">
          <el-card class="filter-card">
            <template #header>
              <div class="filter-header">
                <span>资讯分类</span>
                <el-button link @click="handleResetFilter">重置</el-button>
              </div>
            </template>
            <div class="filter-content">
              <el-radio-group v-model="selectedCategory" @change="handleCategoryChange">
                <el-radio label="">全部 ({{ getCategoryCount('') }})</el-radio>
                <el-radio 
                  v-for="option in classificationOptions" 
                  :key="option.value" 
                  :label="option.value"
                >
                  {{ option.label }} ({{ getCategoryCount(option.value) }})
                </el-radio>
              </el-radio-group>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="allAnnouncements.length"
          :page-size="6"
          layout="total, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Calendar, View, User } from '@element-plus/icons-vue'
import Header from '../../components/header.vue'
import Footer from '../../components/footer.vue'
import { getAllAnnouncements, getAnnouncementsByClassification, classificationOptions, Announcement } from '../../api/announcement'

const router = useRouter()
const loading = ref(false)
const announcements = ref<Announcement[]>([])
const allAnnouncements = ref<Announcement[]>([])
const currentPage = ref(1)
const pageSize = ref(6)
const selectedCategory = ref('')
const originalAnnouncements = ref<Announcement[]>([])

// 格式化日期
const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString()
}

// 获取分类数量
const getCategoryCount = (category: string) => {
  if (!originalAnnouncements.value.length) return 0
  if (category === '') return originalAnnouncements.value.length
  return originalAnnouncements.value.filter(
    announcement => announcement.classification === category
  ).length
}

// 解析资讯内容
const parseAnnouncementText = (text: string) => {
  try {
    // 如果是 JSON 字符串，则解析它
    const parsed = JSON.parse(text)
    return parsed.text || text
  } catch (e) {
    // 如果不是 JSON 字符串，直接返回原文本
    return text
  }
}

// 获取资讯列表
const fetchArticles = async () => {
  loading.value = true
  try {
    let res;
    if (selectedCategory.value) {
      res = await getAnnouncementsByClassification(selectedCategory.value)
    } else {
      res = await getAllAnnouncements()
    }
    
    if (res.code === '200') {
      // 根据分类筛选数据
      const filteredData = selectedCategory.value
        ? res.data.filter(item => item.classification === selectedCategory.value)
        : res.data
      
      // 更新总数据
      allAnnouncements.value = filteredData
      // 只在初始加载时更新原始数据
      if (!selectedCategory.value) {
        originalAnnouncements.value = res.data || []
      }
      handlePagination()
    } else {
      ElMessage.error(res.msg || '获取资讯列表失败')
    }
  } catch (error) {
    console.error('获取资讯列表失败:', error)
    ElMessage.error('获取资讯列表失败')
  } finally {
    loading.value = false
  }
}

// 查看文章详情
const viewDetail = (article: Announcement) => {
  router.push(`/announcement/${article.announcementId}`)
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  handlePagination()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  handlePagination()
}

// 前端分页处理
const handlePagination = () => {
  if (!allAnnouncements.value.length) {
    announcements.value = []
    return
  }
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  announcements.value = allAnnouncements.value.slice(start, end)
  // 确保每页显示固定数量的数据
  if (announcements.value.length < pageSize.value) {
    const emptySlots = pageSize.value - announcements.value.length
    for (let i = 0; i < emptySlots; i++) {
      announcements.value.push({} as Announcement)
    }
  }
  console.log('当前页数据:', announcements.value)
}

// 处理分类变化
const handleCategoryChange = () => {
  currentPage.value = 1
  fetchArticles()
}

// 重置筛选
const handleResetFilter = () => {
  selectedCategory.value = ''
  currentPage.value = 1
  fetchArticles()
}

onMounted(() => {
  console.log('页面已加载，正在获取资讯列表...')
  fetchArticles()
})
</script>

<style scoped>
.information-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.information-content {
  flex: 1;
  width: 1200px;
  margin: 84px auto 40px;
  padding: 0 20px;
}

.information-content h2 {
  margin-bottom: 30px;
  color: #2c3e50;
  text-align: center;
}

.content-layout {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.article-list {
  flex: 1;
  min-width: 0;
}

.category-filter {
  width: 300px;
  flex-shrink: 0;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.filter-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 10px;
}

.filter-content :deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.filter-content :deep(.el-radio) {
  margin-right: 0;
  padding: 8px 15px;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.filter-content :deep(.el-radio:hover) {
  background-color: #f5f7fa;
}

.filter-content :deep(.el-radio__label) {
  flex: 1;
  display: flex;
  justify-content: space-between;
  color: #606266;
}

.article-card {
  margin-bottom: 20px;
  height: 100%;
  transition: transform 0.3s;
  cursor: pointer;
  border-radius: 8px;
  background-color: #fff;
}

.article-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.article-info {
  padding: 20px;
  position: relative;
}

.article-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
  gap: 20px;
}

.article-title {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
  font-weight: bold;
  flex: 1;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-summary {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
  color: #909399;
  font-size: 13px;
  white-space: nowrap;
}

.publish-time,
.author {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination {
  margin-top: 40px;
  display: flex;
  justify-content: center;
}

:deep(.el-pagination) {
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  min-width: 400px;
}

.empty-card {
  height: 200px; /* 与实际卡片高度保持一致 */
  margin-bottom: 20px;
}

.announcement-content {
  color: #606266;
  font-size: 16px;
  line-height: 1.8;
  margin-bottom: 20px;
  white-space: pre-wrap;
  word-break: break-word;
}
</style>